import hashlib
import time
import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from sessionTest.models import Student


def hello(request):
    return HttpResponse('Hello Django')


def login(request):
    if request.method == 'GET':

        return render(request, 'login2.html')

    elif request.method == 'POST':

        username = request.POST.get("username")

        # 将信息存入session中
        request.session["username"] = username

        return HttpResponse("登录成功")


def mine(request):
    username = request.session.get("username")

    return render(request, 'session_mine.html', context=locals())


def logout(request):
    response = redirect(reverse('sessionTest:mine'))

    # 根据sessionid清除cookie
    # response.delete_cookie('sessionid')

    # 可以直接删除session,这两种方式是等价的，体现除了session是基于cookie的原理
    # del request.session['username']

    # 同时删除cookie和session（建议此方法以节约数据库空间）
    request.session.flush()

    return response


def register(request):
    if request.method == 'GET':

        return render(request, 'student_reg.html')

    elif request.method == 'POST':

        username = request.POST.get("username")
        password = request.POST.get("password")

        try:
            student = Student()
            student.s_name = username
            student.s_password = password
            student.save()

        except Exception as e:
            return redirect(reverse("sessionTest:register"))

    return HttpResponse("注册成功")


# 用户登录，同时给登录成功的用户录一个随机的token，以便下次直接识别用户
def studentlogin(request):
    if request.method == 'GET':
        return render(request, 'student_login.html')
    elif request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")

        students = Student.objects.filter(s_name=username).filter(s_password=password)

        if students.exists():
            student = students.first()

            ip = request.META.get("REMOTE_ADDR")

            token = generate_token(ip, username)

            student.s_token = token

            student.save()

            # response = HttpResponse("用户登录成功")
            # response.set_cookie("token",token)
            # return response

            # 移动端用JsonResponse，网页用上面的HttpResponse
            data = {
                "status": 200,
                "msg": "login success!",
                "token": token
            }
            return JsonResponse(data=data)

        # return redirect(reverse("sessionTest:studentlogin"))

        # 移动端用JsonResponse，网页用上面的HttpResponse
        data = {
            "status": 800,
            "msg": "verify failed!",
        }
        return JsonResponse(data=data)


# 生成随即token
def generate_token(ip, username):
    c_time = time.ctime()

    # 将随机数元素拼起来用md5编码，字符集为UTF8,且转成二进制hexdigest
    return hashlib.new("md5", (ip + c_time + username).encode("utf-8")).hexdigest()


# 如果请求的token在数据库中存在，则展现token拥有人的名字，不然跳转回login
def studentmine(request):

    token = request.GET.get("token")

    try:
        student = Student.objects.get(s_token=token)
    except Exception as e:
        redirect(reverse("sessionTest:login"))

    # return HttpResponse(student.s_name)

    # 移动端用JsonResponse，网页用上面的HttpResponse
    data = {
        "msg": "ok",
        "status": 200,
        "data": {
            "username": student.s_name
        }
    }
    return JsonResponse(data=data)
